package com.rzx.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;

@Slf4j
@Component
public class FileUtil {

    @Value("${fs.defaultFS}")
    private String defaultFS;

    @Value("${fs.user}")
    private String user;

    @Value("${fs.dir}")
    private String dir;

    @Autowired
    private Configuration hadoopConfiguration;

    public synchronized void writeFile(String fileName, byte[] b) {
        synchronized (FileUtil.class) {
            try {
                FileSystem fileSystem = FileSystem.get(URI.create(defaultFS), hadoopConfiguration, user);
                Path path = new Path(dir + "/" + fileName);
                FSDataOutputStream out = fileSystem.create(path);
                out.write(b);
                fileSystem.close();
            } catch (IOException | InterruptedException e) {
                log.error("writeFile", e);
            }
        }
    }

    public synchronized byte[] readFile(String fileName) {
        synchronized (FileUtil.class) {
            try {
                Path src = new Path(dir + "/" + fileName);
                FileSystem fileSystem = FileSystem.get(URI.create(defaultFS), hadoopConfiguration, user);
                if (fileSystem.exists(src)) {
                    FSDataInputStream fsDataInputStream = fileSystem.open(src);
                    FileStatus status = fileSystem.getFileStatus(src);
                    byte[] buffer = new byte[Integer.parseInt(String.valueOf(status.getLen()))];
                    fsDataInputStream.readFully(0, buffer);
                    fsDataInputStream.close();
                    fileSystem.close();
                    return buffer;
                }
            } catch (IOException | InterruptedException e) {
                log.error("readFile", e);
            }
        }
        return null;
    }

}
